package beans;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import model.Folder;
import model.Repository;
import model.User;
import conversions.Conversions;
import dao.FolderDao;
import dao.RepositoryDao;
import dao.ServerLogEntryDao;
import dao.UserDao;
import dto.DTOUser;
import dto.RepositoryDTO;
import enumerations.LogType;

/**
 * Session Bean implementation class LoginBean
 * 
 * @author rusho
 */
@Stateless
public class LoginBean implements LoginBeanRemote {

	@EJB
	Conversions conv;

	@EJB
	FolderDao folderDao;

	@EJB
	RepositoryDao repoDao;

	@EJB
	UserDao userDao;
	
	@EJB
	ServerLogEntryDao sleDao;

	DTOUser dtoUser;

	/**
	 * Default constructor.
	 */
	public LoginBean() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 
	 * @param username
	 *            The name of the logged user
	 * @return List of Repositories
	 * 
	 */
	@Override
	public List<RepositoryDTO> populateRepositoryList(String username) {

		List<Repository> repos = new ArrayList<Repository>();

		List<Folder> folder = folderDao.getFoldersForAUser(username);

		if (folder.size() > 0)
			for (Folder f : folder) {

				Repository r = repoDao.getRepositoryByID(f.getId());
				repos.add(r);

			}

		List<RepositoryDTO> rd = conv.repToDTO(repos);

		return rd;

	}

	@Override
	public String findSupervisor(int idRep) {

		List<User> u = userDao.listOfSupervisors(idRep);

		if (u.size() > 0)
			return u.get(0).getName();

		return "invalid";
	}

	@Override
	public DTOUser findDTOUSer(String nameForm) {
		dtoUser = new DTOUser();
		List<User> users = userDao.getUsersByName(nameForm);
		if (users.size() > 0) {
			User u = users.get(0);
			dtoUser.setEmail(u.getEmail());
			dtoUser.setId(u.getId());
			dtoUser.setName(u.getName());
			dtoUser.setPassword(u.getPassword());
			dtoUser.setTelephone(u.getTelephone());
			dtoUser.setType(u.getUserType().toString());
		} else
			dtoUser.setName("invalid user");
		return dtoUser;

	}

	@Override
	public void setPasswordBean(int id, String p) {

		userDao.setProfilePassword(id, p);

		String content="User profile password modified";
		sleDao.insertOpToLog(LogType.modify_user, content, new Date(), userDao.getUserById(id));
	}

}
